package com.yunkaweilai.android.activity.login;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.github.lazylibrary.util.PreferencesUtils;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.MainActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.Umeng;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.CodeMsgBean1;
import com.yunkaweilai.android.model.login.LoginModel;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.NetWorkBroadcast;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.GotoRechargeDialog;

import org.lzh.framework.updatepluginlib.UpdateBuilder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录界面
 * Created by Administrator on 2017/6/19.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.id_edt_username)
    EditText idEdtUsername;
    @BindView(R.id.id_edt_password)
    EditText idEdtPassword;
    @BindView(R.id.id_btn_login)
    TextView idBtnLogin;
    @BindView(R.id.id_check_pass)
    CheckBox idCheckPass;
    @BindView(R.id.tv_save_password)
    TextView tvSavePassword;
    public static final String USERNAME = "USERNAME";
    public static final String PASSWORD = "PASSWORD";
    public static final String ISSAVE = "ISSAVE";
    @BindView(R.id.id_webView)
    WebView idWebView;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.cb_save_password)
    CheckBox cbSavePassword;
    private boolean isSave = false;
    private String APP_UPDATEE = "APP_UPDATE";
    private NetWorkBroadcast netWorkBroadcast = new NetWorkBroadcast();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        StatusBarUtil.setStatusBarTranslucent(this, true); //设置状态栏自适应
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        /*********UMeng********/
        //初始化 s:appkey s1:渠道(写一个自动生成一个)
        UMConfigure.init(mAc, "5d493f620cafb2fd4b000b9d", "Android", UMConfigure.DEVICE_TYPE_PHONE, "");
        // 选用LEGACY_AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_MANUAL);
        // 支持在子进程中统计自定义事件
        UMConfigure.setProcessEvent(true);
        /*********UMeng********/

        PackageInfo pi = null;
        PackageManager pm = getPackageManager();
        try {
            pi = pm.getPackageInfo(getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            BaseApplication.APP_CODE = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        int x = 1;
        int anInt = PreferencesUtils.getInt(mAc, APP_UPDATEE, 0);
        if (x > anInt) {
            //todo:k 首次进入APP设置
            PreferencesUtils.putInt(mAc, APP_UPDATEE, 2);
//            NoTimeDialog dialog = new NoTimeDialog(mAc, "用户协议和隐私条款已更新，请在“5秒快速注册”中点击查看");
//            dialog.show();
        }


        idEdtPassword.setSelection(idEdtPassword.length());
        idEdtUsername.setSelection(idEdtUsername.length());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            isHasInstallPermissionWithO(mAc);//8.0
        }

        UpdateBuilder.create().check();//检查更新

        //保存密码
        tvSavePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cbSavePassword.performClick();
            }
        });
        idCheckPass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    //如果选中，显示密码
                    idEdtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    idEdtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                idEdtPassword.setSelection(idEdtPassword.length());
            }
        });
        cbSavePassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isSave = true;
                } else isSave = false;
            }
        });
        String username = PreferencesUtils.getString(mAc, USERNAME);
        String password = PreferencesUtils.getString(mAc, PASSWORD);
        isSave = PreferencesUtils.getBoolean(mAc, ISSAVE, false);
        cbSavePassword.setChecked(isSave);
        if (!StringUtils.isEmpty(username)) {
            idEdtUsername.setText(username);
        }
        if (!StringUtils.isEmpty(password)) {
            idEdtPassword.setText(password);
        }
//        if (cbSavePassword.isChecked()){//自动登录，但是和自动更新有冲突
//            idBtnLogin.performClick();
//        }
        idEdtUsername.setSelection(idEdtUsername.length());
        idEdtPassword.setSelection(idEdtPassword.length());
        tvVersion.setText("会员-管理-收银-仓管-营销");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private boolean isHasInstallPermissionWithO(Context context) {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    //当网络改变时
    private void networkchange(){
        //核心部分代码
        IntentFilter itFilter = new IntentFilter();
        itFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(netWorkBroadcast, itFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(netWorkBroadcast);
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.LOGIN_URL)
                .addParams("UserName", idEdtUsername.getText().toString())
                .addParams("Password", idEdtPassword.getText().toString())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        idBtnLogin.setClickable(true);
                        dismissProgressDialog();
                        Gson gson = new Gson();
                        CodeMsgBean1 codeMsgBean = gson.fromJson(json, CodeMsgBean1.class);
                        BaseApplication.Zhanghao = idEdtUsername.getText().toString();
                        if (codeMsgBean.getCode() == 0) {
                            showToast(codeMsgBean.getMessage());
                        } else if (codeMsgBean.getCode() == 2) {
                            GotoRechargeDialog dialog = new GotoRechargeDialog(mAc, codeMsgBean.getMessage(), codeMsgBean.getData().getIs_open_store_product() + "", codeMsgBean.getData().getStore_num() + "", "http://pic.91hyk.com/ykwl_v2.0.5_2019092701.apk");
                            dialog.show();
                        } else {
                            MobclickAgent.onEvent(mAc, Umeng.LOGIN);
                            LoginModel loginModel = gson.fromJson(json, LoginModel.class);
                            if (loginModel.getData().getIs_safe_login() == 1) {
                                SafeLoginActivity.actionStart(mAc, loginModel.getData().getEmployee_tel(), idEdtUsername.getText().toString()
                                        , loginModel.getData().getSafe_token());
                                PreferencesUtils.putString(mAc, USERNAME, idEdtUsername.getText().toString());
                                if (isSave) {
                                    PreferencesUtils.putString(mAc, PASSWORD, idEdtPassword.getText().toString());
                                } else {
                                    PreferencesUtils.putString(mAc, PASSWORD, null);
                                }
                            } else {
                                String token = loginModel.getData().getToken() + "";
                                BaseApplication.getInstance().token = token;
                                BaseApplication.getInstance().is_open_lock_member = loginModel.getData().isIs_open_lock_member();
                                BaseApplication.getInstance().member_status = loginModel.getData().getMember_status();
                                PreferencesUtils.putString(mAc, USERNAME, idEdtUsername.getText().toString());
                                PreferencesUtils.putBoolean(mAc, ISSAVE, cbSavePassword.isChecked());
                                if (isSave) {
                                    PreferencesUtils.putString(mAc, PASSWORD, idEdtPassword.getText().toString());
                                } else {
                                    PreferencesUtils.putString(mAc, PASSWORD, null);
                                }
                                initMyInfo();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        idBtnLogin.setClickable(true);
                        dismissProgressDialog();
                        showToast("登录失败");
                    }
                });
    }

    //获取用户信息
    private void initMyInfo() {
        HttpRequest.postUrl(Api.INIT_USER_INFO)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCodeNoLogin(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            UserInfoModel userInfoModel = gson.fromJson(json, UserInfoModel.class);
                            BaseApplication.userInfo = userInfoModel.getData().getStoreEmployeeInfo();
                            getAppRule();
                        } else {
                            dismissProgressDialog();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    //获取权限
    private void getAppRule() {
        HttpRequest.postUrl(Api.APP_RULE)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCodeNoLogin(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            AppRuleModel appRuleModel = gson.fromJson(json, AppRuleModel.class);
                            BaseApplication.appRuleModel = appRuleModel.getData().getInfo();
                            Intent intent = new Intent(mAc, MainActivity.class);
                            startActivity(intent);
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    @OnClick({R.id.id_btn_login, R.id.id_btn_register, R.id.id_tv_forget})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_btn_login://登录
                if (StringUtils.isEmpty(idEdtUsername.getText().toString())) {
                    showToast("请输入帐号");
                } else if (StringUtils.isEmpty(idEdtPassword.getText().toString())) {
                    showToast("请输入密码");
                } else {
                    showProgressDialog("请稍等，正在登录中!");
                    idBtnLogin.setClickable(false);
                    initHttp();
                }
                break;
            case R.id.id_btn_register://注册
                intent2Activity(RegisterActivity.class);
                break;
            case R.id.id_tv_forget://忘记密码
                intent2Activity(ForgetPassActivity.class);
                break;
        }
    }

}